package com.chat.db;

import java.util.Hashtable;

/**
 * 统一操作工厂对象
 * 管理和操作工厂对象
 */
public class SessionFactoryPool {

    private static volatile SessionFactoryPool instance;
    private static volatile Hashtable<String, SessionFactory> sessionFactories;
    private SessionFactoryPool(){
        sessionFactories = new Hashtable<>();
    }

    public static SessionFactoryPool getInstance() {
        if (instance == null) {
            synchronized (SessionFactoryPool.class) {
                if (instance == null) instance = new SessionFactoryPool();
            }
        }
        return instance;
    }

    /**
     * 添加工厂
     * @param key 工厂唯一键
     * @param sessionFactory 工厂对象
     * @return 工厂对象
     */
    public SessionFactory put(String key, SessionFactory sessionFactory) {
        if (isExist(key)) return get(key);

        sessionFactories.put(key, sessionFactory);
        return sessionFactory;
    }

    /**
     * 获取数据工厂
     * @param key 工厂唯一键
     * @return 工厂
     */
    public SessionFactory get(String key) {
        return sessionFactories.get(key);
    }

    /**
     * 检测工厂是否存在
     * @param key 工厂唯一键
     * @return 工厂是否存在
     */
    public boolean isExist(String key) {
        return sessionFactories.containsKey(key);
    }

}
